#ifndef _OHAI_UTILITY_H_
#define _OHAI_UTILITY_H_

/* Utility routines.
 *
 * Copyright 2009 Cian Synnott.
 * 
 * $Id: utility.h 28 2009-12-04 03:01:17Z cian $
 */

/* Set a socket nonblocking.
 *
 * Args:
 * - fd: a socket file descriptor.
 * Returns:
 * - -1 on error or result of fcntl F_SETFL.
 */
int set_nonblocking(int fd);

/* Isolate first space-delimited token in the buffer and return remainder.
 *
 * Note that if the string is e.g. all spaces, both the current string and
 * remainder will end up being empty strings.
 *
 * This function is not a function: it modifies the passed string to terminate
 * it at whitespace.
 *
 * will 
 * Args:
 * - current: buffer to tokenize.
 * Returns: 
 * - pointer to the remaining section of the string.
 */
char *remainder_after_first_token(char *current);

/* Create a pathname with printf-style formatting characters.
 *
 * Allocates a PATH_MAX-sized buffer that must be freed by the caller.
 *
 * Args:
 * - format: a printf-style format string.
 * - ...: variable argument list.
 * Returns:
 * - Newly-allocated and filled-in path buffer or NULL on error.
 */
char *create_path(const char *format, ...);

/* Connect to a local ohaigent via ~/.ohai/socket.
 *
 * Exits with an appropriate log message on error.
 *
 * Args:
 * - quiet: if true, be quiet about errors.
 r Returns:
 * - connected socket ready for use.
 */
int connect_to_ohaigent(int quiet);

/* Write a string to a socket, handling partial writes and logging errors.
 *
 * Args:
 * - fd: the socket file descriptor to write to.
 * - string: the string to write to fd.
 */
void socket_write(int fd, char *string);

/* Read from a socket, handling interrupted reads and logging errors.
 *
 * Args:
 * - fd: the socket file descriptor to read from.
 * - buffer: memory to read into.
 * - size: size of buffer.
 * Returns:
 * - number of bytes read or -1 on error.
 */
int socket_read(int fd, char *buffer, size_t size);

/* If there's a newline at the end of the passed string, kill it.
 *
 * Args:
 * - buffer: string to de-newline.
 */
void kill_newline(char *buffer);

#endif /* _OHAI_UTILITY_H_ */
